import json

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import *
from django.shortcuts import render
from user.models import User

# Create your views here.
from role.models import Role

from role.models import Menu


def init(request: HttpRequest):
    return render(request, 'role/init.html')


def getInit(request: HttpRequest):
    # 表格要展现的数据
    query = request.GET.get("keyword")
    if not query:
        print('a')
        roles = Role.objects.all()
    else:
        print('b')
        roles = Role.objects.filter(name__contains=query)
    # 处理成LayUi官方文档的格式
    lis = []
    for role in roles:
        data = dict()
        data['id'] = role.id
        data['name'] = role.name
        data['desc'] = role.desc
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    role_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    roles = {"code": 0, "msg": "", "count": roles.count(), "data": role_info}
    return JsonResponse(roles)


def preAdd(request: HttpRequest):
    if request.method == "GET":
        return render(request, 'role/add_role.html', locals())
    elif request.method == "POST":
        name = request.POST['name']
        desc = request.POST['desc']
        if Role.objects.filter(name=name):
            return JsonResponse({'state': 0})
        roles = Role.objects.create(
            name=name,
            desc=request.POST["desc"],
        )
        return JsonResponse({'state': "1"})


def del_role(request: HttpRequest):
    uid = request.POST['id']
    role = Role.objects.get(id=uid)
    role.delete()
    return JsonResponse({'state': "1"})


def edit(request: HttpRequest):
    if request.method == "GET":
        uid = request.GET.get
        try:
            role = Role.objects.get
        except:
            return HttpResponseNotFound
        return render(request, 'role/edit_role.html', locals())
    elif request.method == "POST":
        rid = request.POST['id']
        name = request.POST['name']
        desc = request.POST['desc']

        if Role.objects.filter(Q(name=name) & ~Q(id=rid)):
            return JsonResponse({'state': 0})
        try:
            role = Role.objects.get(id=rid)
        except:
            return JsonResponse({'state': 3})
        role.name = name
        role.desc = desc
        role.save()
        return JsonResponse({'state': "1"})


def detail(request: HttpRequest):
    if request.method == "GET":
        uid = request.GET.get('id')
        try:
            role = Role.objects.get(id=uid)
        except:
            return HttpResponseNotFound
        return render(request, 'role/detail_role.html', locals())


def deploy(request: HttpRequest):
    if request.method == "GET":
        rid = request.GET.get('id')
        role=Role.objects.get(id=rid)
        list_per=[]
        for per in role.permissions.all():
            list_per.append(per.id)
        return render(request, 'role/permission.html', locals())


def get_permission(request: HttpRequest):
    menus = Menu.objects.all()
    if not menus:
        return JsonResponse({'code': 30100, 'error': '没有参会人员'})
    personnels = []
    for menu in menus:
        personnel = {}
        personnel['value'] = str(menu.id)
        personnel['title'] = menu.name
        personnels.append(personnel)
    return JsonResponse({"code": 200, 'data': personnels,})

def add_permission(request: HttpRequest):
    json_str = request.body
    obj_str = json.loads(json_str)
    meet_content = obj_str["meet_content"]
    meet_personnel = obj_str['meet_personnel']
    rid=meet_content['rid']
    role = Role.objects.get(id=rid)
    role.permissions.clear()
    for id, person_name in meet_personnel.items():
        # 人员id:1人员名称:admin
        menu = Menu.objects.get(id=id)
        role.permissions.add(menu)
    return JsonResponse({'state': "1"})
